package com.leyou.sms.mq;

import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.*;


/**
 * <h3>leyou-project</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-06-04 20:50
 **/
@Slf4j
@Component
public class SmsListener {
    @Autowired
    private SmsUtils utils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QueueConstants.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = ExchangeConstants.SMS_EXCHANGE_NAME, type = ExchangeTypes.DIRECT),
            key = RoutingKeyConstants.VERIFY_CODE_KEY
    ))
    public void listenerVerifyCodeMessage(Map<String, String> msg){
        if (CollectionUtils.isEmpty(msg)) {
            return ;
        }
        String phone = msg.get("phone");
        if (StringUtils.isEmpty(phone)) {
            return ;
        }
        String code = msg.get("code");
        if (StringUtils.isEmpty(code)) {
            return ;
        }
        try {
            utils.sendVerifyCode(phone, "{\"code\" : " + code + "}");
        } catch (Exception e) {
            log.error("短信发送失败, 原因{}", e.getMessage() );
        }
    }
}
